<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 搜索框 -->
    <!-- 通过v-model指令拿到用户输入的值 -->
    <!-- .native修饰符的作用是，让封装的组件也能够绑定原声的事件 -->
    <el-input placeholder="请输入搜索内容" v-model="searchVal" class="search-input" @keydown.enter.native='searchUser'>
      <el-button slot="append" icon="el-icon-search" @click='searchUser'></el-button>
    </el-input>

    <el-button type="primary" plain @click='addDialogFormVisible =true'>添加用户</el-button>

    <!-- 用户列表 -->
    <!-- 003 获取到的表格数据，必须要给table的data属性 -->
    <!-- 1.4 接收渲染 -->
    <el-table :data="userList" border style="width: 100%" class='mt-15' v-loading='loading'>
      <el-table-column type="index" width="50">
      </el-table-column>
      <el-table-column prop="username" label="姓名">
      </el-table-column>
      <el-table-column prop="email" label="邮箱">
      </el-table-column>
      <el-table-column prop="mobile" label="电话">
      </el-table-column>
      <el-table-column prop="" label="状态">
        <template slot-scope="scope">
          <!-- 此处的v-model应该是scope.row.mg_state -->
          <el-switch v-model="scope.row.mg_state" @change='toggleState(scope.row)' active-color="#13ce66" inactive-color="#ff4949">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column prop="" label="操作">
        <!-- 通过scope.row可以取到表格那一行对象里面的属性 -->
        <template slot-scope="scope">
          <!-- 点击编辑将当前点击用户的所有信息传递到函数中去 -->
          <el-button circle type="primary" icon="el-icon-edit" @click="handleEditUser(scope.row)"></el-button>
          <!-- scope.row.id可以将你点击的那个用户的id获取到，传递给函数发请求-->
          <el-button circle type="danger" icon="el-icon-delete" @click='handleDelUser(scope.row.id)'></el-button>
          <el-button circle type="warning" icon="el-icon-check" @click="handleGrantUser(scope.row)"></el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination class="page mt-15" @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="1" :page-sizes="[10, 20, 30, 40]" :page-size="pagesize" layout="total, sizes, prev, pager, next, jumper" :total="totalNum">
    </el-pagination>

    <!-- 添加用户对话框 -->
    <el-dialog title="添加用户" :visible.sync="addDialogFormVisible ">
      <!-- js表单验证要先给form表单添加ref属性 -->
      <el-form :model="addForm" ref='addFormRef' :rules='myrules'>
        <el-form-item label="用户名" :label-width="formLabelWidth" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" :label-width="formLabelWidth" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" :label-width="formLabelWidth" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" :label-width="formLabelWidth" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogFormVisible  = false">取 消</el-button>
        <el-button type="primary" @click="submitAdd('addFormRef')">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 编辑用户对话框 -->
    <el-dialog title="编辑用户" :visible.sync="editDialogFormVisible ">
      <!-- js表单验证要先给form表单添加ref属性 -->
      <el-form :model="editForm" ref='editFormRef' :rules='myrules'>
        <el-form-item label="用户名" :label-width="formLabelWidth" prop="username">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" :label-width="formLabelWidth" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" :label-width="formLabelWidth" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogFormVisible  = false">取 消</el-button>
        <el-button type="primary" @click="submitEdit('editFormRef')">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 8.1 分配角色对话框 -->
    <el-dialog title="分配角色" :visible.sync="grantDialogFormVisible ">
      <!-- js表单验证要先给form表单添加ref属性 -->
      <el-form :model="grantForm" ref='grantFormRef' :rules='myrules'>
        <el-form-item label="当前用户" :label-width="formLabelWidth" prop="username">
          <el-input v-model="grantForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="选择角色" :label-width="formLabelWidth">
          <!-- 8.3 完成选择器使用，注意lable字段表示的是显示的文字，value表示文字所对应的值，最终用户选了一个选项之后，会将那个选项的value值传给el-select组件中的v-model的变量 -->
          <el-select v-model="selectRoleId" placeholder="请选择">
            <el-option v-for="item in roleList" :key="item.id" :label="item.roleName" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="grantDialogFormVisible  = false">取 消</el-button>
        <el-button type="primary" @click="submitGrant">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>
<script>
// 001 接口统一引入
// 1 导入用户数据列表方法
import {
  getUserList,
  addUser,
  delUser,
  editUser,
  changeState,
  getRoles,
  grantRole
} from '@/api'
export default {
  data () {
    // 定义自定义校验规则所需的函数
    let checkEmail = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入邮箱'))
      } else {
        // 校验邮箱规则 --下面的注释是有特殊意义的，表示检测格式的时候忽略下面的正则语法
        // eslint-disable-next-line
          let emailReg = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
        if (emailReg.test(value)) {
          callback()
        } else {
          callback(new Error('请输入正确的邮箱格式'))
        }
      }
    }
    return {
      searchVal: '',
      userList: [],
      totalNum: 0, // 用户总条数
      pagesize: 10, // 每页显示多少条，默认为10条
      pagenum: 1, // 当前页码，默认为第1页

      addDialogFormVisible: false, // 3.1 添加用户对话框的显示与隐藏
      formLabelWidth: '80px', // 设置input左侧文字的宽度
      // 3.2 添加用户表单的字段
      addForm: {
        username: '',
        password: '',
        emai: '',
        mobile: ''
      },
      editDialogFormVisible: false,
      editForm: {
        id: -1,
        username: '',
        emai: '',
        mobile: ''
      },
      //  8.2 分配角色对话框字段
      grantForm: {
        username: '',
        id: '' // 用户id
      },
      selectRoleId: '', // 选中之后的角色id
      grantDialogFormVisible: false,
      roleList: [], // 角色列表
      myrules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        email: [
          // 自定义校验邮箱规则
          { required: true, validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [{ required: true, message: '请输入电话', trigger: 'blur' }]
      },
      loading: true,
      state: ''
    }
  },
  created () {
    // 1.3 调用初始化table的方法
    this.initTable()
  },
  methods: {
    // 1.2 初始化table数据的方法 --当前实例要加this，不是不用加
    initTable () {
      getUserList({
        query: this.searchVal,
        pagenum: this.pagenum,
        pagesize: this.pagesize
      }).then(res => {
        console.log(res)
        // 2.1 给用户总条数赋值
        this.totalNum = res.data.total
        this.userList = res.data.users
        // 获取完了数据之后，将加载动画隐藏
        // setTimeout(() => {
        this.loading = false
        // }, 1000)
      })
    },
    // 搜索用户
    searchUser () {
      this.initTable()
      this.searchVal = ''
    },
    handleSizeChange (val) {
      console.log(`每页 ${val} 条`)
      // 2.3 改变每页多少条的时候，将这个值赋值给pagesize属性，再调用获取数据的方法
      this.pagesize = val
      this.initTable()
    },
    handleCurrentChange (val) {
      console.log(`当前页: ${val}`)
      // 2.4 改变当前页码时，将当前页码的值赋值给pagenum属性，接着再调用获取数据的方法
      this.pagenum = val
      this.initTable()
    },
    // 提交添加用户方法
    submitAdd (formRef) {
      this.$refs[formRef].validate(isPass => {
        if (isPass) {
          addUser(this.addForm).then(res => {
            if (res.meta.status === 201) {
              this.$message.success('添加用户成功')
              this.addDialogFormVisible = false
              this.addForm.username = ''
              this.addForm.password = ''
              this.addForm.email = ''
              this.addForm.mobile = ''
              this.initTable()
            }
          })
        } else {
          this.$message.warning('请正确填写表单')
        }
      })
    },
    // 删除用户
    handleDelUser (id) {
      // 让提示框显示
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // 点击确定执行的回调函数
          delUser(id).then(res => {
            if (res.meta.status === 200) {
              this.initTable()
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
            } else {
              this.$message.error(res.meta.msg)
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 编辑用户
    handleEditUser (row) {
      this.editForm.id = row.id
      this.editForm.username = row.username
      this.editForm.email = row.email
      this.editForm.mobile = row.mobile
      this.editDialogFormVisible = true
    },
    // 提交编辑
    submitEdit (formRef) {
      // 判断校验是否合法 validate()
      this.$refs[formRef].validate(isPass => {
        if (isPass) {
          editUser(this.editForm).then(res => {
            if (res.meta.status === 200) {
              this.$message.success(res.meta.msg)
              this.editDialogFormVisible = false
              this.initTable()
            }
          })
        } else {
          this.$message.warning('请正确填写表单')
        }
      })
    },
    // 切换状态
    toggleState (row) {
      changeState(row.id, row.mg_state).then(res => {
        this.$message.success(res.meta.msg)
      })
    },
    // 显示分类角色对话框
    handleGrantUser (row) {
      console.log(row)
      this.grantForm.username = row.username
      this.grantForm.id = row.id
      this.grantDialogFormVisible = true
      this.selectRoleId = row.role_name // 此处是为了解决点击显示分配角色弹窗时，每个用户默认角色一样的bug
      // 8.4 调用接口获取角色列表
      // console.log(row)
      getRoles().then(res => {
        // 8.5 在data中定义变量，将获取的角色列表保存起来
        // console.log(res)
        this.roleList = res.data
      })
    },
    // 提交分配角色
    submitGrant () {
      // 8.7 发请求之前，先判断selectRoleId是否为字符串，如果为字符串说明用户没有更改角色，直接return就行了
      if (typeof this.selectRoleId === 'string') {
        this.grantDialogFormVisible = false
        return false
      }
      // 8.6 发请求分配角色
      grantRole(this.grantForm.id, this.selectRoleId).then(res => {
        console.log(res)
        this.$message.success(res.meta.msg)
        this.initTable() // 必须刷新表格
        this.grantDialogFormVisible = false
      })
    }
  }
}
</script>
<style lang="scss" scoped>
  .search-input {
    width: 300px;
  }
</style>
